package com.study.shiro.config;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Set;

/**
 * 自定义过滤器, 默认 roles[admin,root] 是需要两者角色才可以访问, 修改为只要具有一个角色就可以访问
 *
 * @author huanggy
 * @date 2020/2/10 14:16
 */
public class CustomerRolesFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = super.getSubject(servletRequest, servletResponse);
        String[] rolesArray = (String[]) o;
        if (rolesArray != null && rolesArray.length != 0) {
            Set<String> roles = CollectionUtils.asSet(rolesArray);
            for (String role : roles) {
                if (subject.hasRole(role)) {
                    return true;
                }
            }
            return false;
        } else {
            return true;
        }
    }
}
